var utils = require("../Utils/utils")
var model = require("../DAO/model")
var md5 = require("md5")
var multer = require("multer")
var session = require('express-session')



module.exports.changePwd =  function(req, res) {

	model.User.findOne({
		email: req.session.userInfo.email
	}, function(err, doc) {
		if(!err) {
			if(doc.password == md5(md5(req.body.password))) {
				model.User.updateOne({
					email: req.session.userInfo.email
				}, {
					$set: {
						password: md5(md5(req.body.newpwd))
					}
				}, function(err) {
					if(!err) {
						res.send({
							info: "修改成功！"
						})
					} else {
						res.send({
							info: "修改失败！"
						})
					}
				})

			} else {
				res.send({
							info: "原密码不正确！"
						})
			}
		} else {
			res.send({
							info: "修改失败！"
						})
		}
	})
}


module.exports.changeName =  function(req, res) {
	model.User.updateOne({
		email: req.session.userInfo.email
	}, {
		$set: {
			name: req.body.name
		}
	}, function(err) {
		if(!err) {
			req.session.userInfo.name = req.body.name
			res.send({
				info: "修改成功！",
				name:req.session.userInfo.name,
				avatar:req.session.userInfo.avatar
			})
		} else {
			res.send({
				info: "修改失败！"
			})
		}
	})

}






module.exports.changeAvatar =  function(req,res){
     if (req.file.length === 0) {  //判断一下文件是否存在，也可以在前端代码中进行判断。
        res.send( {info: "上传文件不能为空！"});
        
    } else {
      let file = req.file;
      
      avatar = "/img/avatar/"+file.filename
      req.session.userInfo.avatar = avatar
		model.User.updateOne({
		email: req.session.userInfo.email
	}, {
		$set: {
			avatar: req.session.userInfo.avatar 
		}
	},function(err){})
      
       res.send( {info: "上传成功！",avatar:req.session.userInfo.avatar});
    }
    
}

